package com.bestillet.kyllingogco;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

public class CardActivity extends Activity {
	private ArrayList<Stamp> stamps;
	
	private GridView grid;
	private TextView title;
	private Context context;
	private Button back, home;

	private SharedPreferences preferences;
	private ShopApplication app;
	private LoadingDialog loading;
	private CardTask task;
	private Card card;
	
	private String name;
	
	private int idx;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.card);

		app = (ShopApplication) getApplicationContext();
		context = this;

		preferences = getSharedPreferences("Kylling & Co", MODE_PRIVATE);
		
		name = getIntent().getExtras().getString("title");
		idx = getIntent().getExtras().getInt("idx", -1);
		
		grid = (GridView) findViewById(R.id.stamps);
		
		title = (TextView) findViewById(R.id.lblTitle);
		title.setText(name);
		
		back = (Button) findViewById(R.id.btnBack);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		home = (Button) findViewById(R.id.btnHome);
		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		int i = 0;
		boolean found = false;
		
		while (!found && i < app.getCards().size()) {
			if (idx == app.getCards().get(i).getIdx())
				found = true;
			else
				i++;
		}
		
		if (found) {
			card = app.getCards().get(i);
		}
		
		loading = new LoadingDialog(this);
		loading.show();
		
		task = new CardTask();
		task.execute();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (task != null)
			if (task.getStatus() == Status.RUNNING)
				task.cancel(true);
	}
	
	private class CardTask extends AsyncTask<Void, Void, Boolean> {
    	@Override
		protected Boolean doInBackground(Void... params) {
    		try {
				String phone = preferences.getString("phone", "");
    			InputStream in = Server.post(Server.STAMPS, Server.getAuthenticationStamps(phone, idx));
    			XmlPullParser parser = Server.toXmlParser(in);
    			stamps = XmlParser.getStamps(parser);
    			in.close();
    		} catch (IOException e) {
    			Log.e("Shop", "IOException: " + e.getMessage());
    			return false;
    		} catch (XmlPullParserException e) {
    			Log.e("Shop", "XmlPullParserException: " + e.getMessage());
    			return false;
    		} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
    			return false;
    		} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
    		return true;
    	}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	if (success) {
	    		CardArrayAdapter adapter = new CardArrayAdapter(context, card, stamps.size());
	    		grid.setAdapter(adapter);
	    	} else {
	    		AlertDialog.Builder builder = new AlertDialog.Builder(context);
	    		builder.setMessage(R.string.error_stamps)
	    		       .setTitle(R.string.error)
	    		       .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								task = new CardTask();
								task.execute();
								loading.show();
							}
						})
						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						});
	    		AlertDialog dialog = builder.create();
	    		dialog.show();
	    	}
	    	
			loading.dismiss();
	    }
	}
}